#!/usr/bin/env node

/**
 * 语音通话调试测试脚本
 * 用于测试移动端到PC端的语音通话邀请流程
 */

const io = require('socket.io-client')

const API_BASE = process.env.API_BASE || 'http://localhost:3000'

async function testVoiceCallFlow() {
  console.log('🎤 开始测试语音通话流程...')
  
  // 模拟移动端用户
  const mobileUserId = 'test_mobile_user_123'
  const mobileSocket = io(API_BASE, { query: { userId: mobileUserId } })
  
  // 模拟PC端医生
  const doctorUserId = 'doctor_test_doctor_456'
  const doctorSocket = io(API_BASE, { query: { userId: doctorUserId } })
  
  let testPassed = false
  
  // 设置PC端监听
  doctorSocket.on('voice:incoming', (payload) => {
    console.log('✅ PC端收到语音通话邀请:', payload)
    testPassed = true
    cleanup()
  })
  
  // 等待连接建立
  await new Promise((resolve) => {
    let connectedCount = 0
    const checkConnection = () => {
      connectedCount++
      if (connectedCount === 2) {
        console.log('✅ 两个Socket连接已建立')
        resolve()
      }
    }
    
    mobileSocket.on('connect', () => {
      console.log('📱 移动端Socket已连接')
      checkConnection()
    })
    
    doctorSocket.on('connect', () => {
      console.log('💻 PC端Socket已连接')
      checkConnection()
    })
  })
  
  // 等待一下确保房间加入完成
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟移动端发送语音通话邀请
  console.log('📤 移动端发送语音通话邀请...')
  const callId = `voice_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  mobileSocket.emit('voice:forward', {
    to: doctorUserId,
    callId: callId,
    from: mobileUserId,
    fromName: '测试用户'
  })
  
  // 等待响应
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  if (testPassed) {
    console.log('🎉 语音通话流程测试通过！')
  } else {
    console.log('❌ 语音通话流程测试失败：PC端未收到邀请')
  }
  
  function cleanup() {
    mobileSocket.disconnect()
    doctorSocket.disconnect()
    process.exit(testPassed ? 0 : 1)
  }
}

// 运行测试
testVoiceCallFlow().catch(console.error)
